package com.hkccommunity.controller;

import com.alibaba.fastjson.JSON;
import com.hkccommunity.common.Code;
import com.hkccommunity.common.R;
import com.hkccommunity.entity.User;
import com.hkccommunity.service.UserService;
import com.hkccommunity.service.impl.UserServiceImpl;
import com.hkccommunity.util.DateConversionUtil;
import com.hkccommunity.util.JsonSwitchUtil;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.*;
import java.time.Instant;
import java.time.LocalDateTime;


@WebServlet( urlPatterns = "/login/*")
@MultipartConfig
public class LoginController extends BaseController {

    private UserService service = new UserServiceImpl();

    public void getUserByUser(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{

        HttpSession session = req.getSession();
        session.setMaxInactiveInterval(30*60);
        BufferedReader reader = req.getReader();
        String line = reader.readLine();
        User parseObject = JSON.parseObject(line, User.class);
        User user = service.getUserByPhone(parseObject.getPhone());

        R res = new R();
        if (user != null && user.getPassword().equals(parseObject.getPassword())){
            session.setAttribute("user",user);
            res.setCode(Code.POST_SUCCESS);
            user.setPassword("");
            res.setData(user);
            res.setMessage("登入成功");
        }else if (user == null){
            res.setCode(Code.POST_ERROR);
            res.setMessage("该用户不存在！！！");
        }else {
            res.setCode(Code.POST_ERROR);
            res.setMessage("账号或者密码错误!!!");
        }

        JsonSwitchUtil.toJsonSting(req,resp,res);

    }

    public void upload(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{

        Part part = req.getPart("upload");
        String fileName = part.getSubmittedFileName();
        int i = fileName.lastIndexOf(".");
        String substring = fileName.substring(i);
        StringBuffer requestURL = req.getRequestURL();
        String uri = req.getRequestURI();
        int indexOf = requestURL.lastIndexOf(uri);
        String imgPath = requestURL.substring(0, indexOf) + req.getContextPath() + "/images/public/";
//        System.out.println(uri + "  " + requestURL);
        long id = Instant.now().getEpochSecond();
        try (
                InputStream inputStream = part.getInputStream();
                OutputStream outputStream = new BufferedOutputStream(new FileOutputStream("E:\\JetBrains\\IdeaProjects\\hkccommunity\\src\\main\\webapp\\images\\public\\" + id + substring));
                OutputStream os = new BufferedOutputStream(new FileOutputStream("E:\\JetBrains\\IdeaProjects\\hkccommunity\\target\\hkccommunity\\images\\public\\" + id + substring))
                ){
            int len;
            byte[] bytes = new byte[1024];
            while ((len = inputStream.read(bytes)) != -1) {
                os.write(bytes,0,len);
                outputStream.write(bytes, 0, len);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        JsonSwitchUtil.toJsonSting(req,resp,imgPath + id + substring);

    }

    public void register(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{

        HttpSession session = req.getSession();
        BufferedReader reader = req.getReader();
        String line = reader.readLine();
        User user = JSON.parseObject(line, User.class);

        Instant now = Instant.now();
        Long id = now.toEpochMilli();
        user.setId(id);

        System.out.println(user);
        int i = service.insertUser(user);
        R r = new R();
        if (i == 1){
            User user1 = service.getUserByPhone(user.getPhone());
            user1.setPassword("");
            session.setAttribute("user",user1);
            r.setCode(Code.POST_SUCCESS);
            r.setMessage("注册成功,已登入");
            r.setData(user1);
        }else {
            r.setCode(Code.POST_ERROR);
            r.setMessage("该号码已经注册过了！！！");
        }

        JsonSwitchUtil.toJsonSting(req,resp,r);

    }

    /**
     * 是否处于登入状态
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    public void isLogin(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        HttpSession session = req.getSession();
        User user = (User) session.getAttribute("user");
        R r = new R();
        if (user != null){
            r.setCode(Code.POST_SUCCESS);
            r.setData(user);
        }else {
            r.setCode(Code.POST_ERROR);
            r.setMessage("请先登入！！！");
        }
        JsonSwitchUtil.toJsonSting(req,resp,r);
    }

    public void exitLogin(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{

        HttpSession session = req.getSession();
        session.invalidate();
        R r = new R();

        r.setCode(Code.GET_SUCCESS);
        r.setMessage("退出登入成功");

        JsonSwitchUtil.toJsonSting(req,resp,r);
    }
}
